package cc.liyinghao.security.util;

import cc.liyinghao.common.bo.SysUserDetails;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;


public class SecurityUtil {
    /**
     * 获取当前登录用户id
     */
    public static int getCurrentUserId() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication != null && authentication.getPrincipal() instanceof SysUserDetails) {
            SysUserDetails userDetails = (SysUserDetails) authentication.getPrincipal();
            return userDetails.getUser().getId();
        } else {
            throw new RuntimeException("获取当前用户id失败");
        }
    }

    /**
     * 获取当前登录用户名
     */
    public static String getCurrentUsername() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication != null && authentication.getPrincipal() instanceof SysUserDetails) {
            SysUserDetails userDetails = (SysUserDetails) authentication.getPrincipal();
            return userDetails.getUsername();
        } else {
            throw new RuntimeException("获取当前用户名失败");
        }
    }
}

